package com.example.yichuangyun.ui.fragment;

import static android.app.Activity.RESULT_OK;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.example.yichuangyun.R;
import com.example.yichuangyun.config.Constant;
import com.example.yichuangyun.databinding.FragmentMineBinding;
import com.example.yichuangyun.dialog.DownloadDialog;
import com.example.yichuangyun.dialog.MyDialog;
import com.example.yichuangyun.dialog.VersionUpdateDialog;
import com.example.yichuangyun.http.HttpRespond;
import com.example.yichuangyun.http.MyObserver;
import com.example.yichuangyun.http.RetrofitHelper;
import com.example.yichuangyun.model.VersionModel;
import com.example.yichuangyun.model.business.LabelModel;
import com.example.yichuangyun.mvvm.base.BaseFragment;
import com.example.yichuangyun.mvvm.ui.activity.AddressBookActivity;
import com.example.yichuangyun.mvvm.ui.activity.MyCollectActivity;
import com.example.yichuangyun.mvvm.ui.activity.order.OrderListActivity;
import com.example.yichuangyun.ui.activity.follow.FollowListActivity;
import com.example.yichuangyun.ui.activity.mine.QrActivity;
import com.example.yichuangyun.ui.activity.mine.QuestionActivity;
import com.example.yichuangyun.ui.fragment.view.MineViewModel;
import com.example.yichuangyun.utils.AppUtils;
import com.example.yichuangyun.utils.CommonUtil;
import com.example.yichuangyun.utils.DownLoadHelper;
import com.example.yichuangyun.utils.JumpIntent;
import com.example.yichuangyun.utils.ToastHelper;
import com.example.yichuangyun.utils.pictrue.GlideEngine;
import com.example.yichuangyun.utils.pictrue.ImageLoaderUtils;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.config.SelectModeConfig;
import com.luck.picture.lib.engine.CompressFileEngine;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.style.PictureSelectorStyle;
import com.yalantis.ucrop.UCrop;
import com.yalantis.ucrop.UCropImageEngine;

import java.io.File;
import java.io.Serializable;
import java.util.List;

import top.zibin.luban.Luban;
import top.zibin.luban.OnNewCompressListener;

/**
 * 我的
 */
public class MineFragment extends BaseFragment<FragmentMineBinding, MineViewModel> {

    private ActivityResultLauncher<Intent> launcherResult;
    private MyDialog myDialog;
    private VersionUpdateDialog versionUpdateDialog;
    private String downApkUrl;

    @Override
    protected MineViewModel bindModel() {
        return getViewModel(this, MineViewModel.class);
    }

    @Override
    protected void initInject() {
        getFragmentComponent().inject(this);
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void initData() {
        launcherResult = createActivityResultLauncher();
        binding.tvVersionCode.setText(Constant.VERSION);
        initDialog();
        viewModel.getUserInfo();
    }

    private void initDialog() {
        myDialog = new MyDialog(getActivity()) {
            @Override
            public void rightClick() {
                // 投机取巧，相当于解绑了个推的cid
                RetrofitHelper.getInstance().execute(RetrofitHelper.getService().bindCid("1"));
                new Handler().postDelayed(() -> CommonUtil.jumpToLogin(getActivity()), 100);
            }
        };
        myDialog.setContent(mContext.getString(R.string.confirm_logout));

        versionUpdateDialog = new VersionUpdateDialog(getActivity()) {
            @Override
            public void confirm() {
                downloadApk(downApkUrl);
                dismissDialog();
            }
        };
    }

    @Override
    protected void initClick() {
        viewModel.onDelayClick(binding.rlHead, o -> PictureSelector.create(mContext).openGallery(SelectMimeType.ofImage()) // 全部.SelectMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .setImageEngine(GlideEngine.createGlideEngine()) // 外部传入图片加载引擎，必传项
                .setSelectorUIStyle(new PictureSelectorStyle())
                .setCameraImageFormat(PictureMimeType.PNG) // 拍照保存图片格式后缀,默认jpeg,Android Q使用PictureMimeType.PNG_Q
                .setSelectionMode(SelectModeConfig.SINGLE) // 单选
                .setCropEngine((fragment, srcUri, destinationUri, dataSource, requestCode) -> { // 裁剪
                    UCrop.Options options = new UCrop.Options();
                    options.withAspectRatio(1, 1);
                    UCrop uCrop = UCrop.of(srcUri, destinationUri, dataSource);
                    uCrop.withOptions(options);
                    uCrop.setImageEngine(new UCropImageEngine() {
                        @Override
                        public void loadImage(Context context, String url, ImageView imageView) {
                            if (!ImageLoaderUtils.assertValidRequest(context)) {
                                return;
                            }
                            Glide.with(context).load(url).override(180, 180).into(imageView);
                        }

                        @Override
                        public void loadImage(Context context, Uri url, int maxWidth, int maxHeight, OnCallbackListener<Bitmap> call) {
                            Glide.with(context).asBitmap().load(url).override(maxWidth, maxHeight).into(new CustomTarget<Bitmap>() {
                                @Override
                                public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                                    if (call != null) {
                                        call.onCall(resource);
                                    }
                                }

                                @Override
                                public void onLoadCleared(@Nullable Drawable placeholder) {
                                    if (call != null) {
                                        call.onCall(null);
                                    }
                                }
                            });
                        }
                    });
                    uCrop.start(fragment.requireActivity(), fragment, requestCode);
                })
                .setCompressEngine((CompressFileEngine) (context, source, call) -> Luban.with(context).load(source).ignoreBy(100) // 小于多少kb的图片不压缩
                        .setCompressListener(new OnNewCompressListener() {
                            @Override
                            public void onStart() {
                            }

                            @Override
                            public void onSuccess(String source, File compressFile) {
                                if (call != null) {
                                    call.onCallback(source, compressFile.getAbsolutePath());
                                }
                            }

                            @Override
                            public void onError(String source, Throwable e) {
                                if (call != null) {
                                    call.onCallback(source, null);
                                }
                            }
                        }).launch())
                .forResult(launcherResult));

        viewModel.onDelayClick(binding.rlMyCollect, o -> JumpIntent.jump(getActivity(), MyCollectActivity.class));

        viewModel.onDelayClick(binding.rlMyAddressBook, o -> RetrofitHelper.getInstance().execute(RetrofitHelper.getService().getContactsType(), new MyObserver<HttpRespond<List<LabelModel>>>() {
            @Override
            protected void onSuccess(HttpRespond<List<LabelModel>> listHttpRespond) {
                if (listHttpRespond.code == Constant.SUCCESS) {
                    List<LabelModel> list = listHttpRespond.data;
                    if (null != list && list.size() > 0) {
                        Bundle bundle = new Bundle();
                        bundle.putSerializable(Constant.listKey, (Serializable) list);
                        JumpIntent.jump(getActivity(), AddressBookActivity.class, bundle);
                    } else {
                        ToastHelper.show(mContext.getString(R.string.no_permission));
                    }
                }
            }
        }));

        viewModel.onDelayClick(binding.rlMyOrderList, o -> JumpIntent.jump(getActivity(), OrderListActivity.class));

        viewModel.onDelayClick(binding.rlMyFollow, o -> JumpIntent.jump(getActivity(), FollowListActivity.class));

        viewModel.onDelayClick(binding.rlQr, o -> JumpIntent.jump(getActivity(), QrActivity.class));

        viewModel.onDelayClick(binding.rlQuestion, o -> JumpIntent.jump(getActivity(), QuestionActivity.class));

        viewModel.onDelayClick(binding.rlVersion, o -> checkVersionUpdate());

        viewModel.onDelayClick(binding.tvLogout, o -> myDialog.showDialog());

        viewModel.urlMutableLiveData.observe(this, s -> Glide.with(mContext).load(s).placeholder(R.mipmap.default_head).into(binding.ivHead));

        viewModel.userInfoModelMutableLiveData.observe(this, userInfoModel -> {
            if (userInfoModel != null) {
                binding.setUserInfoModel(userInfoModel);
                binding.tvUserInfo.setText(mContext.getString(R.string.user_info, userInfoModel.getJobNumber(),
                        userInfoModel.getGender() == 1
                                ? (mContext.getString(R.string.sex_boy))
                                : mContext.getString(userInfoModel.getGender() == 2 ? R.string.sex_girl : R.string.unknown),
                        userInfoModel.getPhone()));
                Glide.with(mContext).load(userInfoModel.getThumbAvatar()).placeholder(R.mipmap.default_head).into(binding.ivHead);
                if (!TextUtils.isEmpty(userInfoModel.getEntryTime())) {
                    binding.tvEntryTime.setText(mContext.getString(R.string.entry_time_mao,
                            userInfoModel.getEntryTime().length() > 10
                                    ? userInfoModel.getEntryTime().substring(0, 10)
                                    : userInfoModel.getEntryTime()));
                } else {
                    binding.tvEntryTime.setVisibility(View.GONE);
                }
            }
        });
    }

    /**
     * 检查版本更新
     */
    private void checkVersionUpdate() {
        RetrofitHelper.getInstance().execute(RetrofitHelper.getService().getVersionInfo(), new MyObserver<HttpRespond<VersionModel>>() {
            @Override
            protected void onSuccess(HttpRespond<VersionModel> versionModelHttpRespond) {
                if (versionModelHttpRespond.code == Constant.SUCCESS) {
                    if (null != versionModelHttpRespond.data) {
                        int currentVersion = Integer.parseInt(AppUtils.getVersionName(mContext).replace(".", ""));
                        int serviceVersion = Integer.parseInt(versionModelHttpRespond.data.getVersion().replace(".", ""));
                        if (currentVersion < serviceVersion) {
                            downApkUrl = versionModelHttpRespond.data.getDownYcyAppUrl();
                            versionUpdateDialog.setVersion(versionModelHttpRespond.data.getVersion());
                            versionUpdateDialog.showDialog();
                        } else {
                            ToastHelper.show(mContext.getString(R.string.latest_version));
                        }
                    }
                }
            }
        });
    }

    private void downloadApk(String apkUrl) {
        if (null != getActivity()) {
            // 截取apk的名称，如yky.apk
            String destFileName = apkUrl.substring(apkUrl.lastIndexOf("/") + 1);
            final File filesDir = getActivity().getExternalFilesDir("upgrade");
            // 如果文件不存在新建一个
            if (!filesDir.exists()) {
                filesDir.mkdirs();
            }
            final String filePath = filesDir.getPath() + "/";
            DownloadDialog downloadDialog = new DownloadDialog(getActivity());
            downloadDialog.showDialog();
            DownLoadHelper.getInstance()
                    .download(apkUrl, filePath, new DownLoadHelper.OnDownloadListener() {
                        @Override
                        public void onDownloadSuccess(String path) {
                            downloadDialog.dismissDialog();
                            if (!XXPermissions.isGrantedPermission(mContext, Permission.REQUEST_INSTALL_PACKAGES)) {
                                ToastHelper.show(getString(R.string.install_permission));
                                new Handler().postDelayed(() -> XXPermissions.with(mContext)
                                        .permission(Permission.REQUEST_INSTALL_PACKAGES)
                                        .request((permissions, all) -> CommonUtil.installAPK(mContext, filePath + destFileName)), 2000);
                            } else {
                                CommonUtil.installAPK(getActivity(), filePath + destFileName);
                            }
                        }

                        @Override
                        public void onDownloading(int progress) {
                            downloadDialog.setProgress(progress);
                        }

                        @Override
                        public void onDownloadFailed() {
                            downloadDialog.dismissDialog();
                        }
                    });
        }
    }

    /**
     * 创建一个ActivityResultLauncher
     */
    private ActivityResultLauncher<Intent> createActivityResultLauncher() {
        return registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            int resultCode = result.getResultCode();
            if (resultCode == RESULT_OK) {
                List<LocalMedia> selectList = PictureSelector.obtainSelectorList(result.getData());
                for (int i = 0; i < selectList.size(); i++) {
                    LocalMedia media = selectList.get(i);
                    File file = new File(media.getCompressPath() == null ? media.getRealPath() : media.getCompressPath());
                    viewModel.uploadImages(file);
                }
            }
        });
    }
}
